package com.lhkj.ct.framework.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import java.io.IOException;

/**
 * CSRF跨站伪造攻击过滤器
 *
 * @Date: 2023-08-21
 */

//@WebFilter(urlPatterns = "/*", filterName = "aFilter")
public class CSRFFilter implements Filter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

//    private XTSZService xtszService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        this.xtszService = SpringContextHolder.getBean(XTSZServiceImpl.class);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
//        XTSZVo xtszVo = xtszService.selectOne();
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        if (!validRequest(request, xtszVo)) {
//            JsonResult<String> result = new JsonResult<>(ResultStatus.CODE_500, xtszVo.getCSRF_TIPS());
//            RequestUtil.printWriter(response, result);
//            return;
//        }
        chain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }

//    private boolean validRequest(HttpServletRequest request, XTSZVo xtszVo) {
//        List<String> ips = new ArrayList<>(xtszVo.getCSRF_WHITE_LIST());
//        // 加入本地服务器地址
//        ips.add("127.0.0.1");
//        ips.add("localhost");
//        // 加入本地服务器地址
//        if (!ips.contains("localhost")) {
//            ips.add("localhost");
//        }
//        // 判断是否需要过滤的请求方式
//        if (!xtszVo.getCSRF_METHOD_LIST().contains(request.getMethod())) {
//            return true;
//        }
//        // 请求来源验证
//        String referer = request.getHeader("referer");
//        // 如果来源为null
//        if (StringUtils.isBlank(referer)) {
//            return false;
//        }
//        try {
//            URI uri = new URI(referer);
//            // 如果来源为null且不是白名单时
//            return ips.stream().anyMatch(p -> RequestUtil.validIp(p, uri.getHost()));
//        } catch (URISyntaxException e) {
//            logger.error(ExceptionUtils.getStackTrace(e));
//            return false;
//        }
//    }
}
